package org.person.gift.listener;

import com.alibaba.fastjson.JSONArray;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.person.gift.constants.GiftConstants;
import org.person.gift.service.IGoodsSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQTransactionListener(txProducerGroup = GiftConstants.GIFT_OFFSALE_TX_PRODUCER_GROUP)
public class SpuOffsaleRocketMQLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IGoodsSpuService goodsSpuService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //从消息对象中获取数据的字节对象
            byte[] bytes = (byte[])message.getPayload();
            //转化为字符串
            String jsonStr = new String(bytes,"utf-8");
            //转化为集合
            List<Long> offsaleIds = JSONArray.parseArray(jsonStr, Long.class);

            boolean result = goodsSpuService.executeOffsaleLocalTransactionOpr(offsaleIds);
            return result?RocketMQLocalTransactionState.COMMIT:RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            //从消息对象中获取数据的字节对象
            byte[] bytes = (byte[])message.getPayload();
            //转化为字符串
            String jsonStr = new String(bytes,"utf-8");
            //转化为集合
            List<Long> offsaleIds = JSONArray.parseArray(jsonStr, Long.class);
            boolean result = goodsSpuService.checkExsitOffsaled(offsaleIds);
            return result?RocketMQLocalTransactionState.COMMIT:RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
